import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const dataDir = path.join(__dirname, '..', 'data');

// 读取数据文件
function readJSONFile(filename) {
    const filePath = path.join(dataDir, filename);
    try {
        const content = fs.readFileSync(filePath, 'utf8');
        return JSON.parse(content);
    } catch (error) {
        console.error(`读取文件失败 ${filename}:`, error);
        return [];
    }
}

// 写入数据文件
function writeJSONFile(filename, data) {
    const filePath = path.join(dataDir, filename);
    fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
    console.log(`✓ 已更新 ${filename}`);
}

async function rebuildUserRoles() {
    console.log('开始重建用户角色关联...\n');

    // 读取现有数据
    const users = readJSONFile('users.json');
    const teachers = readJSONFile('teachers.json');
    const students = readJSONFile('students.json');
    const roles = readJSONFile('roles.json');

    // 获取角色ID映射
    const roleMap = {};
    roles.forEach(role => {
        roleMap[role.code] = role.id;
    });

    // 创建phone到teacher/student的映射
    const phoneToTeacher = {};
    teachers.forEach(teacher => {
        if (teacher.phone) {
            phoneToTeacher[teacher.phone] = teacher;
        }
    });

    const phoneToStudent = {};
    students.forEach(student => {
        if (student.phone) {
            phoneToStudent[student.phone] = student;
        }
    });

    // 重建userRoles
    const userRoles = [];
    let userRoleId = 1;

    users.forEach(user => {
        // 根据用户的role字段或phone匹配确定角色
        let assignedRoleId = null;

        if (user.role === 'admin') {
            assignedRoleId = roleMap.admin;
        } else if (user.role === 'teacher' || phoneToTeacher[user.phone]) {
            assignedRoleId = roleMap.teacher;
        } else if (user.role === 'student' || phoneToStudent[user.phone]) {
            assignedRoleId = roleMap.student;
        }

        if (assignedRoleId) {
            userRoles.push({
                id: userRoleId++,
                userId: user.id,
                roleId: assignedRoleId,
                createdAt: new Date().toISOString()
            });
            console.log(`✓ 用户 ${user.username} (ID: ${user.id}) -> 角色ID ${assignedRoleId} (${roles.find(r => r.id === assignedRoleId)?.name})`);
        } else {
            console.log(`⚠️  用户 ${user.username} (ID: ${user.id}) 没有匹配到角色`);
        }
    });

    // 保存更新后的数据
    console.log('\n保存数据...');
    writeJSONFile('userRoles.json', userRoles);

    console.log(`\n✅ 完成！`);
    console.log(`  - 总用户数: ${users.length}`);
    console.log(`  - 总角色关联数: ${userRoles.length}`);
    console.log(`  - 管理员: ${userRoles.filter(ur => ur.roleId === roleMap.admin).length} 个`);
    console.log(`  - 教师: ${userRoles.filter(ur => ur.roleId === roleMap.teacher).length} 个`);
    console.log(`  - 学生: ${userRoles.filter(ur => ur.roleId === roleMap.student).length} 个`);
}

// 执行脚本
rebuildUserRoles().catch(error => {
    console.error('执行失败:', error);
    process.exit(1);
});

